package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.math.BigDecimal;
import java.util.Arrays;

import static com.shanxia.codec.CodeConstant.PERCENT;
import static com.shanxia.codec.Decoder.*;

/**
 * C -> S
 * 充电桩上传命令请求
 * 充电桩根据应用场景向后台服务器发送请求数据
 */
@Data
public class Cmd10 extends ProtocolDataBase {

    public static final int MIN_SIZE = 41;

    private int v1;
    private int v2;
    private String sn;                         // 充电桩编码
    private int pileNum;                       // 充电枪号
    private int requestAddr;                   // 请求启始地址
    private String data;                      // 参数

    public Cmd10(){
        super.setCmd(10);
    }

    public static Cmd10 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd10 cmd = new Cmd10();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 32字节充电桩编码
        cmd.sn = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 32), true);
        offset += 32;
        // 1字节充电枪号
        cmd.pileNum = getUint8(dataField[offset++]);
        // 4字节请求起始地址
        cmd.requestAddr = bytesToIntLittle(dataField, offset);
        offset += 4;
        // 4N字节数据
        switch (cmd.requestAddr) {
            // 4字节请求生成预付费支付二维码, 单位0.01元
            case 1:
            // 4字节预留，单位0.01元
            case 2:
                int amount = bytesToIntLittle(dataField, offset);
                cmd.data = String.valueOf(new BigDecimal(amount).multiply(PERCENT).doubleValue());
                break;
            default:
                break;
        }
        return cmd;
    }

    @Override
    public String toString() {

        StringBuffer buffer = new StringBuffer();
        buffer.append("#cmd10#").append("\n");
        buffer.append("v1:").append(v1).append("\n");
        buffer.append("v2:").append(v2).append("\n");
        buffer.append("充电桩编码:").append(sn).append("\n");
        buffer.append("充电枪号:").append(pileNum).append("\n");
        buffer.append("请求启始地址:").append(requestAddr).append("\n");
        buffer.append("参数:").append(data).append("\n");
        return buffer.toString();
    }
}
